﻿using System;
using System.Collections.Generic;
using System.Web.Security;
using PetaPoco;
using doufu.Common;
using doufu.Common.Extensen;
using doufu.Model;
using doufu.Model.ViewModel;

namespace doufu.Service
{
    public class UserServices : IUserBusiness<users>
    {
        public users Details(int id)
        {
            return CommonDac.Query(db => db.SingleOrDefault<users>(id));
        }

        public users Details(string openId)
        {
            return CommonDac.Query(db => db.SingleOrDefault<users>("where openId=@openId", new { openId }));
        }

        public Page<users> Pager(int page)
        {
            return CommonDac.Query(db => db.Page<users>(page, 5, "select * from users order by user_id desc"));
        }

        public bool Save(users entity)
        {
            return CommonDac.Query(db =>
                {
                    if (entity.user_id == 0)
                    {
                        entity.created_at = DateTime.Now;
                        entity.last_login = DateTime.Now;
                        db.Insert(entity);
                    }
                    else
                    {
                        db.Update(entity, new List<string> { "user_status", "user_name" });
                    }
                    return true;
                });
        }

        #region Permission
        public permission PermissionDetails(int id)
        {
            return CommonDac.Query(db => db.SingleOrDefault<permission>(id));
        }

        public Page<permission> PermissionPager(int page)
        {
            return CommonDac.Query(
                    db => db.Page<permission>(page, 10, "select * from permission order by permission_id desc"));
        }

        public bool PermissionSave(permission entity, IUser u)
        {
            if (entity.permission_id == 0)
            {
                entity.created_by = u.user.UserId;
            }

            return CommonDac.Query(db =>
            {
                if (entity.permission_id == 0)
                {
                    entity.created_at = DateTime.Now;
                    db.Insert(entity);
                }
                else
                {
                    db.Update(entity, new List<string> { "permission_code", "permission_name", "show_in_menu", "parent_id" });
                }
                return true;
            });
        }
        #endregion

        #region UserPermission
        public List<UserPermission> UserPermission(int userId)
        {
            return CommonDac.Query(db => db.Fetch<UserPermission>("select p.permission_id,p.permission_name,ifnull(up.user_permission_id,0) has_permission,@0 user_id from permission p left join user_permission up on p.permission_id=up.permission_id and up.user_id=@0", userId));
        }
        public bool SaveUserPermission(int userId, int permissionId, IUser user)
        {
            return CommonDac.Query(
                  db =>
                  {
                      var count = db.ExecuteScalar<int>(
                           "select count(*) from user_permission where user_id=@0 and permission_id=@1",
                           userId, permissionId);
                      if (count > 0)
                      {
                          db.Delete<user_permission>("where user_id=@0 and permission_id=@1", userId, permissionId);
                      }
                      else
                      {
                          db.Insert(new user_permission
                          {
                              permission_id = permissionId,
                              user_id = userId,
                              created_at = DateTime.Now,
                              created_by = user.user.UserId
                          });
                      }
                      return true;
                  });

        }
        #endregion

        #region Login
        public users GetByNameAndPassword(string name, string password)
        {
            return
                CommonDac.Query(
                    db =>
                    db.SingleOrDefault<users>(string.Format("where user_name=@username and password=@password"),
                                              new { username = name, password = password.ToMd5() }));
        }

        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("值不能为 null 或为空。", "userName");
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        public users GetOpenUser(string openId, int type)
        {
            return CommonDac.Query(
                    db =>
                    db.SingleOrDefault<users>(string.Format("where openId=@openid and openType=@authtype"),
                                              new { openid = openId, authtype = type }));
        }
        #endregion
    }
}

